from datetime import date, timedelta

from flask import Blueprint

from zvms.models import Student, Volunteer, StuVol, ActivationCode
from zvms.deco import *
from zvms.res import *
from zvms.util import *

student = Blueprint('student', __name__)

@student.route('/student/volbook/<int:stuId>', methods=['GET'])
@Deco
def getStudentWork(stuId, json_data, token_data):
    r = Student.query.get_or_error(stuId, '该学生没有义工记录').volunteers
    if not r:
        return error('该学生没有义工记录')
    return success('获取成功', rec=r)

@student.route('/student/volcert', methods=['POST'])
@Deco
def getVolunteerCertification(json_data, token_data):
    r1 = (StuVol.query.get_or_error((json_data['volId'], json_data['stuId']))
        .select('status', 'thought', stuId='id', volTimeInside='inside', volTimeOutside='outside', volTimeLarge='large'))
    r2 = Volunteer.query.get_or_error(json_data['volId']).select('description', volId='id', volName='name', volTime='time', volDate='date',
        volTimeInside='inside', volTimeOutside='outside', volTimeLarge='large')
    return success('获取成功', stu=r1, vol=r2)

@student.route('/student/activate/<int:stuId>', methods=['POST'])
@Deco
def activate_account(stuId, json_data, token_data):
    code = json_data['code']
    if ActivationCode.query.get(code) is None:
        return error('无效的激活码')
    Student.query.get_or_error(stuId).activated_until = date.today() + timedelta(365)
    ActivationCode.query.filter_by(code=code).delete()
    return success('激活成功')